import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:mall/core/models/protocol.dart';
import 'package:mall/core/providers/app_model.dart';
import 'package:mall/routes.dart';
import 'package:mall/screens/main/main_page.dart';
import 'package:mall/screens/mine/login_page.dart';

class DioInterceptor extends InterceptorsWrapper {
  // 忽略协议
  static const _ignoreProtocol = [
    "/s/oauth/token",
    "/s/me",
    "/api/logistics",
  ];
  final AppModel appModel;

  DioInterceptor(this.appModel);

  @override
  Future onRequest(RequestOptions options) async {
    options.headers['bindingStoreId'] = appModel.bindingStoreId;
    options.headers['currentStoreId'] = appModel.currentStoreId;
    options.headers['Authorization'] = 'Bearer ${appModel.accessToken}';
    return options;
  }

  @override
  Future onResponse(Response response) async {
    if (_ignoreProtocol.contains(response.request.path)) {
      return response;
    }
    var protocol = Protocol.fromJson(response.data);
    if (protocol.code == 0) {
      response.data = protocol.data;
      return response;
    } else {
      throw protocol.message ?? '未知信息';
    }
  }

  @override
  Future onError(DioError err) async {
    if (err.response?.statusCode == 400 && err.request.path == '/s/oauth/token') {
      return '账号或密码错误';
    }
    if (err.response?.statusCode == 401) {
      Routes.navigatorKey.currentState.pushNamedAndRemoveUntil(
        LoginPage.routeName,
        ModalRoute.withName(MainPage.routeName),
      );
      return '登录已失效，请重新登录';
    }
    if (err.error is SocketException) {
      return '服务器升级中，请稍后...';
    }
    if (err.error is HttpException) {
      return "服务器升级中，请稍后...";
    }
    return err.message;
  }
}
